#include "Arduino.h"
#include "WiFi_AT.h"
#include "ESP_AT_Lib.h"
#include "ArduinoJson.h"
#include "lvgl.h"

UART Serial_2(20, 21, 0, 0);
extern UART SerialDebug;

#define EspSerial Serial_2

ESP8266 wifi(&EspSerial);
#define WiFiDebug SerialDebug


bool wifi_init(void)
{
    EspSerial.begin(ESP_AT_BAUD);

    WiFiDebug.print("FW Version:");
    WiFiDebug.println(wifi.getVersion().c_str());
   
    WiFiDebug.print("Set AP/STA Mode ");
    if (wifi.setOprToStationSoftAP())
    {
        WiFiDebug.println("OK");
        return 1;
    }
    else
    {
        WiFiDebug.println("failed");
        return 0;
    }
    return 0;
}

bool wifi_connecting(void)
{
    WiFiDebug.print("Join WiFi ");
    if (wifi.joinAP(SSID, PASSWORD))
    {
        WiFiDebug.println("Connect to WiFi OK");
        WiFiDebug.print("IP: ");
        WiFiDebug.println(wifi.getLocalIP().c_str());
        return 1;
    }
    else
    {
        WiFiDebug.println("Connect to WiFi failed");
        return 0;
    }
    return 0;
}

uint8_t * wifi_TCP(char *location)
{
    SerialDebug.println("Create TCP ");

    if (wifi.createTCP(HOST_NAME, HOST_PORT)) 
        WiFiDebug.println("OK");
    else 
        WiFiDebug.println("failed");
    
    // malloc recieve buffer
    uint8_t *buffer;
    buffer = (uint8_t *)malloc(1024 * sizeof(uint8_t));

    char GET[256] = {0};
    sprintf(GET, "GET http://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=en&unit=c\r\n\r\n"
                , KEY, location);
    
    WiFiDebug.println(GET);
    wifi.send((const uint8_t*)GET, strlen(GET));

    uint32_t len = wifi.recv(buffer, 1024, 2000);

    if (len > 0) 
    {
        WiFiDebug.println("=========================Received============================");

        for (uint32_t i = 0; i < len; i++) 
        {
            SerialDebug.print((char) buffer[i]);
        }
        WiFiDebug.println("\n============================================================");
    }
    else
    {
        WiFiDebug.println("=========================Failed============================");
    }
    // 释放TCP连接
    if (wifi.releaseTCP()) 
    {
        WiFiDebug.println("Release TCP OK");
    }     
    return buffer;
}

void GetWeather(char *location, Weather_Info_t *info)
{
    // Get TCP data
    uint8_t *buffer;
    buffer = wifi_TCP(location);

    // json process
    const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + 2*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 230;
    DynamicJsonDocument doc(capacity);
    DeserializationError error = deserializeJson(doc, buffer);
    if(!error)
    {
        JsonObject results_0 = doc["results"][0];

        JsonObject results_0_now = results_0["now"];

        info->text = (char *)malloc(strlen(results_0_now["text"]));
        info->code = (char *)malloc(strlen(results_0_now["code"]));
        info->temp = (char *)malloc(strlen(results_0_now["temperature"]));
        info->update = (char *)malloc(strlen(results_0["last_update"]));

        strcpy(info->text, results_0_now["text"]);  // "Sunny"
        strcpy(info->code, results_0_now["code"]);  // "0"
        strcpy(info->temp, results_0_now["temperature"]);  // "32"
        strcpy(info->update, results_0["last_update"]);  // "2020-06-02T14:40:00+08:00" 
        
        WiFiDebug.print(" now text ");SerialDebug.println(info->text);
        WiFiDebug.print(" now code ");SerialDebug.println(info->code);
        WiFiDebug.print(" now tem ");SerialDebug.println(info->temp);
        WiFiDebug.print(" last updata ");SerialDebug.println(info->update);
    }
    else
    {
        WiFiDebug.println("Arduinojson error");
    }
    doc.clear();  // free Arduinojson Data
    
    free(buffer);  // free buffer Data
}


